package com.suse.service.community.controller;

import cn.hutool.core.util.ObjectUtil;
import com.suse.common.config.response.ApiException;
import com.suse.common.util.cos.CosUtil;
import com.suse.service.community.entity.User;
import com.suse.service.community.service.FollowService;
import com.suse.service.community.service.LikeService;
import com.suse.service.community.service.UserService;
import com.suse.service.community.util.UserHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * <p>
 * 用户前端控制器
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-08-31 11:06
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private LikeService likeService;

    @Resource
    private FollowService followService;

    @GetMapping("/setting.html")
    public String getSettingPage() {
        return "site/setting";
    }

    @PostMapping("/upload")
    public String upload(MultipartFile file, Model model) {
        if (ObjectUtil.isNull(file)) {
            model.addAttribute("error","您还没有选择图片！");
            return "site/setting";
        }
        String url = CosUtil.upload(file);
        User user = UserHolder.getUser();
        userService.updateHeader(user.getId(),url);
        return "redirect:/user/setting.html";
    }

    @GetMapping("/profile/{userId}")
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.getUserById(userId);
        if (ObjectUtil.isNull(user)) {
            throw new ApiException("该用户不存在！");
        }
        // 用户信息
        model.addAttribute("user",user);
        // 点赞数
        int likeCount = likeService.getUserLikeCount(userId);
        model.addAttribute("likeCount",likeCount);
        // 关注人数
        long attentionsCount = followService.getAttentionsCount(userId);
        model.addAttribute("attentionsCount",attentionsCount);
        // 粉丝人数
        long followersCount = followService.getFollowersCount(userId);
        model.addAttribute("followersCount",followersCount);
        // 是否已关注
        boolean hasFollowed = followService.hasFollowed(userId);
        model.addAttribute("hasFollowed",hasFollowed);
        return "site/profile";
    }

}
